package com.workerhelping.utils;


import com.workerhelping.result.Result;
import com.workerhelping.result.ResultCodeEnum;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;

import java.util.HashMap;
import java.util.Map;

public class SendMessageUtil {
    public static Result<String> sendShortMessage(String host, String path, String method, String mobile, String appCode, String smsSignId, String templateId) {
        //生成验证码
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 4; i++)
            code.append((int) (Math.random() * 10));
        Map<String, String> headers = new HashMap<>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appCode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", mobile);
        querys.put("param", "**code**:" + code + ",**minute**:5");
        querys.put("smsSignId", smsSignId);
        querys.put("templateId", templateId);
        Map<String, String> bodys = new HashMap<>();

        String reasonPhrase = null;
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            StatusLine statusLine = response.getStatusLine();
            // 状态码
            int statusCode = statusLine.getStatusCode();
            // 消息
            reasonPhrase = statusLine.getReasonPhrase();
            if (statusCode == 200)
                return Result.ok(code.toString());
            return Result.build(null,ResultCodeEnum.REGISTER_CODE_SEND_ERROR);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.build(201,e.getMessage());
        }
    }

}
